import java.util.Arrays;

public class Solution {
    public static int monotoneIncreasingDigits(int n) {
        String str = Integer.toString(n);
        int len = str.length();
        char[] ch = str.toCharArray();

        char[] ret = new char[len];
        int p = 0;//指针
        boolean flag = false;
        while (p < len - 1) {
            ret[p] = ch[p];
            if (ch[p] <= ch[p + 1]) {
                p++;
            } else {
                // if (p == 0) {
                //     flag = true;
                //     ret[p] = (char)(ch[p] - 1);
                //     break;
                // }
                flag = true;
                while (p - 1 >= 0 && ret[p] == ret[p - 1]) {//回退找相同的数
                    // flag = true;
                    p--;
                }
                ret[p] = (char)(ch[p] - 1);
                break;
            }
        }

        if (!flag) {//没有相同的数
            ret[len - 1] = ch[len - 1];
        } else {//有相同的数
            p++;
            while (p < len) {
                ret[p++] = '9';
            }
        }


        return Integer.parseInt(new String(ret));

    }

    public static void main(String[] args) {
        System.out.println(monotoneIncreasingDigits(10));
    }
}
